package putao.server
{
	import flash.events.EventDispatcher;
	import flash.events.NetStatusEvent;
	import flash.net.GroupSpecifier;
	import flash.net.NetConnection;
	import flash.net.NetGroup;
	import flash.utils.clearTimeout;
	import flash.utils.getTimer;
	import flash.utils.setTimeout;
	
	import putao.debug.Debug;

	public class Server extends EventDispatcher
	{
		private var nc:NetConnection;
		private var group:NetGroup;
		private var groupSep:GroupSpecifier;
		private var setupTime:uint = 0;
		
		public function Server()
		{
			//connect();
		}
		
		public function connect():void
		{
			nc = new NetConnection();
			nc.connect("rtmfp:");
			nc.addEventListener(NetStatusEvent.NET_STATUS,statusFun);
		}
		
		private function setGroup():void
		{
			var d:Date = new Date();
			setupTime = d.time;
			groupSep = new GroupSpecifier("myGroup");
			groupSep.multicastEnabled = true;
			groupSep.ipMulticastMemberUpdatesEnabled = true;
			groupSep.postingEnabled = true;
			groupSep.serverChannelEnabled = true;
			groupSep.addIPMulticastAddress("230.0.0.1:9322");
			//======================================================
			//groupSep.addBootstrapPeer(Global.getInstance().userName);
			group = new NetGroup(nc,groupSep.groupspecWithAuthorizations());
			group.addEventListener(NetStatusEvent.NET_STATUS,statusFun);
			Debug.getInstance().appendMsg("创建组成功");
			//Debug.getInstance().appendMsg("用户名："+Global.getInstance().userName);
		}
		
		private function statusFun(e:NetStatusEvent):void
		{
			switch (e.info.code)
			{
				case "NetConnection.Connect.Success" :
					setGroup();
					break;
				case "NetGroup.Connect.Success" :
					connectSuccess();
					break;
				case "NetGroup.Neighbor.Connect" :
					neighborConnect();
					break;
				case "NetGroup.Posting.Notify" :
					receiveMessage(e.info.message);
					break;
			}
		}
		
		private function connectSuccess():void
		{
			//Global.getInstance().testTF.text = "connect success";
			Debug.getInstance().appendMsg("连接组成功");
		}
		
		private var iTimeOut:uint;
		
		private function neighborConnect():void
		{
			Debug.getInstance().appendMsg("邻居数量："+group.neighborCount);
			iTimeOut = setTimeout(postSetupTime, 100);
		}
		
		private function postSetupTime():void
		{
			clearTimeout(iTimeOut);
			var obj:Object=new Object();
			obj.type="gettime";
			obj.setupTime=setupTime;
			group.post(obj);
		}
		
		private function receiveMessage(message:Object):void
		{
			switch(message.type)
			{
				case "gettime":
					Debug.getInstance().appendMsg("邻居连接时间："+message.setupTime);
					break;
				default:
					break;
			}
		}
	}
}